//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_idea_api_serv

import (
	"context"
	"time"

	"atomgit.com/openlinksaas-org/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas-org/api-server/dao"
	"atomgit.com/openlinksaas-org/api-server/dao/idea_dao"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/idea_store_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

func (apiImpl *IdeaStoreAdminApiImpl) CreateIdea(ctx context.Context, req *idea_store_api.AdminCreateIdeaRequest) (*idea_store_api.AdminCreateIdeaResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &idea_store_api.AdminCreateIdeaResponse{
			Code:   idea_store_api.AdminCreateIdeaResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &idea_store_api.AdminCreateIdeaResponse{
			Code:   idea_store_api.AdminCreateIdeaResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.IdeaStorePerm.CreateIdea {
		return &idea_store_api.AdminCreateIdeaResponse{
			Code:   idea_store_api.AdminCreateIdeaResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := idea_dao.IdeaStoreDao.Exist(ctx, req.IdeaStoreId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &idea_store_api.AdminCreateIdeaResponse{
			Code:   idea_store_api.AdminCreateIdeaResponse_CODE_NO_STORE,
			ErrMsg: "知识点仓库不存储",
		}, nil
	}

	ideaId := uuid.NewString()
	nowTime := time.Now().UnixNano() / 1e6

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = idea_dao.StoreIdeaDao.Insert(sessCtx, &idea_dao.IdeaInStoreDbItem{
			IdeaId: ideaId,
			BasicInfo: idea_dao.BasicIdeaDbItem{
				Title:       req.BasicInfo.Title,
				Content:     req.BasicInfo.Content,
				KeywordList: []string{},
			},
			IdeaStoreId: req.IdeaStoreId,
			TimeStamp:   nowTime,
		})
		if err != nil {
			return nil, err
		}
		count, err := idea_dao.StoreIdeaDao.Count(sessCtx, &idea_store_api.ListIdeaParam{
			FilterByStoreId: true,
			StoreId:         req.IdeaStoreId,
		})
		if err != nil {
			return nil, err
		}
		err = idea_dao.IdeaStoreDao.UpdateIdeaCount(sessCtx, req.IdeaStoreId, count)
		if err != nil {
			return nil, err
		}
		return &idea_store_api.AdminCreateIdeaResponse{
			Code:   idea_store_api.AdminCreateIdeaResponse_CODE_OK,
			IdeaId: ideaId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*idea_store_api.AdminCreateIdeaResponse), nil
}

func (apiImpl *IdeaStoreAdminApiImpl) UpdateIdea(ctx context.Context, req *idea_store_api.AdminUpdateIdeaRequest) (*idea_store_api.AdminUpdateIdeaResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &idea_store_api.AdminUpdateIdeaResponse{
			Code:   idea_store_api.AdminUpdateIdeaResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &idea_store_api.AdminUpdateIdeaResponse{
			Code:   idea_store_api.AdminUpdateIdeaResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.IdeaStorePerm.UpdateIdea {
		return &idea_store_api.AdminUpdateIdeaResponse{
			Code:   idea_store_api.AdminUpdateIdeaResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := idea_dao.StoreIdeaDao.Exist(ctx, req.IdeaId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &idea_store_api.AdminUpdateIdeaResponse{
			Code:   idea_store_api.AdminUpdateIdeaResponse_CODE_NO_IDEA,
			ErrMsg: "知识点不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = idea_dao.StoreIdeaDao.UpdateBasicInfo(sessCtx, req.IdeaId, &idea_dao.BasicIdeaDbItem{
			Title:       req.BasicInfo.Title,
			Content:     req.BasicInfo.Content,
			KeywordList: []string{},
		})
		if err != nil {
			return nil, err
		}
		return &idea_store_api.AdminUpdateIdeaResponse{
			Code: idea_store_api.AdminUpdateIdeaResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*idea_store_api.AdminUpdateIdeaResponse), nil
}

func (apiImpl *IdeaStoreAdminApiImpl) MoveIdea(ctx context.Context, req *idea_store_api.AdminMoveIdeaRequest) (*idea_store_api.AdminMoveIdeaResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &idea_store_api.AdminMoveIdeaResponse{
			Code:   idea_store_api.AdminMoveIdeaResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &idea_store_api.AdminMoveIdeaResponse{
			Code:   idea_store_api.AdminMoveIdeaResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.IdeaStorePerm.MoveIdea {
		return &idea_store_api.AdminMoveIdeaResponse{
			Code:   idea_store_api.AdminMoveIdeaResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	ideaItem, err := idea_dao.StoreIdeaDao.Get(ctx, req.IdeaId)
	if err != nil {
		return &idea_store_api.AdminMoveIdeaResponse{
			Code:   idea_store_api.AdminMoveIdeaResponse_CODE_NO_IDEA,
			ErrMsg: "知识点不存在",
		}, nil
	}
	exist, err := idea_dao.IdeaStoreDao.Exist(ctx, req.IdeaStoreId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &idea_store_api.AdminMoveIdeaResponse{
			Code:   idea_store_api.AdminMoveIdeaResponse_CODE_NO_STORE,
			ErrMsg: "知识点仓库不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = idea_dao.StoreIdeaDao.UpdateIdeaStore(sessCtx, req.IdeaId, req.IdeaStoreId)
		if err != nil {
			return nil, err
		}
		{
			count, err := idea_dao.StoreIdeaDao.Count(sessCtx, &idea_store_api.ListIdeaParam{
				FilterByStoreId: true,
				StoreId:         ideaItem.IdeaStoreId,
			})
			if err != nil {
				return nil, err
			}
			err = idea_dao.IdeaStoreDao.UpdateIdeaCount(sessCtx, ideaItem.IdeaStoreId, count)
			if err != nil {
				return nil, err
			}
		}
		{
			count, err := idea_dao.StoreIdeaDao.Count(sessCtx, &idea_store_api.ListIdeaParam{
				FilterByStoreId: true,
				StoreId:         req.IdeaStoreId,
			})
			if err != nil {
				return nil, err
			}
			err = idea_dao.IdeaStoreDao.UpdateIdeaCount(sessCtx, req.IdeaStoreId, count)
			if err != nil {
				return nil, err
			}
		}
		return &idea_store_api.AdminMoveIdeaResponse{
			Code: idea_store_api.AdminMoveIdeaResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*idea_store_api.AdminMoveIdeaResponse), nil
}

func (apiImpl *IdeaStoreAdminApiImpl) RemoveIdea(ctx context.Context, req *idea_store_api.AdminRemoveIdeaRequest) (*idea_store_api.AdminRemoveIdeaResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &idea_store_api.AdminRemoveIdeaResponse{
			Code:   idea_store_api.AdminRemoveIdeaResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &idea_store_api.AdminRemoveIdeaResponse{
			Code:   idea_store_api.AdminRemoveIdeaResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.IdeaStorePerm.RemoveIdea {
		return &idea_store_api.AdminRemoveIdeaResponse{
			Code:   idea_store_api.AdminRemoveIdeaResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	ideaItem, err := idea_dao.StoreIdeaDao.Get(ctx, req.IdeaId)
	if err != nil { //记录不存在
		return &idea_store_api.AdminRemoveIdeaResponse{
			Code: idea_store_api.AdminRemoveIdeaResponse_CODE_OK,
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = idea_dao.StoreIdeaDao.Remove(sessCtx, req.IdeaId)
		if err != nil {
			return nil, err
		}
		count, err := idea_dao.StoreIdeaDao.Count(sessCtx, &idea_store_api.ListIdeaParam{
			FilterByStoreId: true,
			StoreId:         ideaItem.IdeaStoreId,
		})
		if err != nil {
			return nil, err
		}
		err = idea_dao.IdeaStoreDao.UpdateIdeaCount(sessCtx, ideaItem.IdeaStoreId, count)
		if err != nil {
			return nil, err
		}
		return &idea_store_api.AdminRemoveIdeaResponse{
			Code: idea_store_api.AdminRemoveIdeaResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*idea_store_api.AdminRemoveIdeaResponse), nil
}

func (apiImpl *IdeaStoreAdminApiImpl) ListIdea(ctx context.Context, req *idea_store_api.AdminListIdeaRequest) (*idea_store_api.AdminListIdeaResponse, error) {
	emptyList := []*idea_store_api.IdeaInStore{}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &idea_store_api.AdminListIdeaResponse{
			Code:     idea_store_api.AdminListIdeaResponse_CODE_WRONG_SESSION,
			ErrMsg:   "会话不存在",
			IdeaList: emptyList,
		}, nil
	}
	if !sess.AuthOk {
		return &idea_store_api.AdminListIdeaResponse{
			Code:     idea_store_api.AdminListIdeaResponse_CODE_NOT_AUTH,
			ErrMsg:   "未授权会话",
			IdeaList: emptyList,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.IdeaStorePerm.Read {
		return &idea_store_api.AdminListIdeaResponse{
			Code:     idea_store_api.AdminListIdeaResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			IdeaList: emptyList,
		}, nil
	}
	count, err := idea_dao.StoreIdeaDao.Count(ctx, req.ListParam)
	if err != nil {
		return nil, err
	}
	ideaItemList, err := idea_dao.StoreIdeaDao.List(ctx, req.ListParam, int64(req.Offset), int64(req.Limit), -1)
	if err != nil {
		return nil, err
	}

	ideaList := []*idea_store_api.IdeaInStore{}
	for _, ideaItem := range ideaItemList {
		ideaList = append(ideaList, ideaItem.ToIdeaInStore())
	}

	return &idea_store_api.AdminListIdeaResponse{
		Code:       idea_store_api.AdminListIdeaResponse_CODE_OK,
		TotalCount: count,
		IdeaList:   ideaList,
	}, nil
}

func (apiImpl *IdeaStoreAdminApiImpl) GetIdea(ctx context.Context, req *idea_store_api.AdminGetIdeaRequest) (*idea_store_api.AdminGetIdeaResponse, error) {
	emptyIdea := &idea_store_api.IdeaInStore{
		BasicInfo: &idea_store_api.BasicIdea{},
	}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &idea_store_api.AdminGetIdeaResponse{
			Code:   idea_store_api.AdminGetIdeaResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
			Idea:   emptyIdea,
		}, nil
	}
	if !sess.AuthOk {
		return &idea_store_api.AdminGetIdeaResponse{
			Code:   idea_store_api.AdminGetIdeaResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
			Idea:   emptyIdea,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.IdeaStorePerm.Read {
		return &idea_store_api.AdminGetIdeaResponse{
			Code:   idea_store_api.AdminGetIdeaResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
			Idea:   emptyIdea,
		}, nil
	}

	ideaItem, err := idea_dao.StoreIdeaDao.Get(ctx, req.IdeaId)
	if err != nil {
		return &idea_store_api.AdminGetIdeaResponse{
			Code:   idea_store_api.AdminGetIdeaResponse_CODE_NO_IDEA,
			ErrMsg: "知识点不存在",
			Idea:   emptyIdea,
		}, nil
	}

	return &idea_store_api.AdminGetIdeaResponse{
		Code: idea_store_api.AdminGetIdeaResponse_CODE_OK,
		Idea: ideaItem.ToIdeaInStore(),
	}, nil
}
